﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Content;

namespace XNA_Game_Framework
{
	public class ScreenManager
	{
		Game gameRef;
		GraphicsDeviceManager graphics;
		Stack<Screen> screens;
		ThemeManager themes;

		public Screen CurrentScreen
		{
			get
			{
				if (screens.Count > 0)
				{
					return screens.Peek();
				}
				else
				{
					return null;
				}
			}
		}

		public ThemeManager Themes
		{
			get { return themes; }
		}

		public ScreenManager(Game game, GraphicsDeviceManager graphics)
		{
			gameRef = game;
			this.graphics = graphics;
			screens = new Stack<Screen>();
			themes = new ThemeManager();
		}

		public Screen AddScreen(string name)
		{
			DisableCurrentScreen();

			Screen newScreen = new Screen(gameRef, graphics, this, themes, name);

			screens.Push(newScreen);

			return newScreen;
		}

		public Screen AddScreen(Type screensClass)
		{
			DisableCurrentScreen();

			object[] parameters = new object[] { gameRef, this };
			Screen newScreen = (Screen)Activator.CreateInstance(screensClass, parameters);
			newScreen.Graphics = graphics;

			screens.Push(newScreen);

			return newScreen;
		}

		public void AddExistingScreen(Screen screen)
		{
			DisableCurrentScreen();

			if (screen.Graphics == null)
			{
				screen.Graphics = graphics;
			}

			screens.Push(screen);
		}

		public void DisableCurrentScreen()
		{
			if (screens.Count > 0)
			{
				CurrentScreen.Enabled = false;
			}
		}

		public void RemoveScreen()
		{
			if (screens.Count > 1)
			{
				screens.Pop();
				CurrentScreen.InputHandler.Update();
				CurrentScreen.Enabled = true;
			}
		}

		/// <summary>
		/// Draws all controls on current screen
		/// </summary>
		public void Draw()
		{
			CurrentScreen.Draw();
		}

		/// <summary>
		/// Runs the inputHandler of the current screen
		/// </summary>
		public void Update(GameTime gameTime)
		{
			CurrentScreen.Update(gameTime);
		}
	}
}
